package com.zoo.boot.controller;

import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import com.zoo.boot.api.CommonResult;
import com.zoo.boot.api.PagingDto;
import com.zoo.boot.bean.UserEntity;
import com.zoo.boot.model.LUser;
import com.zoo.boot.service.RoleService;
import com.zoo.boot.service.UserService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;

import java.util.List;
import java.util.Map;

/**
 * @Author: WangB
 * @Date: 2021/6/25
 */
@Controller
@Api(tags = "SysUserController", value = "用户管理")
@RequestMapping("/sys/user")
public class SysUserController {

    @Autowired
    private UserService userService;

    @Autowired
    private RoleService roleService;

    @GetMapping("/index")
    @ApiOperation("展示用户主页面")
    public String index() {
        return "system/user/user";
    }

    @GetMapping("/list")
    @ResponseBody
    @ApiOperation("查询用户列表")
    public CommonResult lists(PagingDto dto, LUser user) {
        Page<Object> objects = PageHelper.startPage(dto.getPage(), dto.getLimit());
        List<LUser> lUsers = userService.selectUsers(user);
        return CommonResult.tableSuccess(lUsers).setCount(objects.getTotal());
    }





    @PreAuthorize("hasAnyAuthority('user:add')")
    @GetMapping("/add")
    @ApiOperation("展示新增页面")
    public String navAddPage(Map map) {
        map.put("userInfo", new LUser());
        //展示角色列表
        map.put("roles", roleService.getRoles());
        return "system/user/user-add";
    }

    @PostMapping
    @ResponseBody
    @ApiOperation("添加用户信息")
    public CommonResult add(@RequestBody UserEntity userEntity) {
        if (userService.insertUser(userEntity)) {
            return CommonResult.success();
        }
        return CommonResult.fail();
    }


    @PreAuthorize("hasAnyAuthority('user:update')")
    @GetMapping("/edit")
    @ApiOperation("展示修改页面")
    public String navUpdatePage(Integer userId, Map map) {
        map.put("userInfo", userService.selectUserById(userId));
        map.put("roles", roleService.getRoles());
        return "system/user/user-edit";
    }

    @PutMapping
    @ResponseBody
    @ApiOperation("修改用户信息")
    public CommonResult update(@RequestBody UserEntity userEntity) {
        if (userService.updateUser(userEntity)) {
            return CommonResult.success();
        }
        return CommonResult.fail();
    }


    @PreAuthorize("hasAnyAuthority('user:del')")
    @DeleteMapping
    @ResponseBody
    @ApiOperation("删除用户信息")
    public CommonResult delete(Integer userId) {
        if (userService.deleteUserById(userId))
            return CommonResult.success();
        return CommonResult.fail();
    }
}
